package com.MinesweeperGame.server;


import java.util.List;


import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.http.HttpSession;


import com.MinesweeperGame.client.LoginInfo;
import com.MinesweeperGame.client.LoginService;
import com.MinesweeperGame.client.UserInfo;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class LoginServiceImpl extends RemoteServiceServlet implements
LoginService {
	
	
	@Override
   public Boolean searchUser(String uname, String password) throws IllegalArgumentException {
		
		String username = uname;
		
		PersistenceManager pm = LocalPersistanceManager.getPersistenceManager();

		
		HttpSession httpSession = getThreadLocalRequest().getSession(true);
		httpSession.setAttribute("userName", username);
		    
		    try {
		    	   Query     query   =  pm.newQuery(MinesweeperRegistration.class,"UserName == uname && Password == uPassword");
		    	    query.declareParameters("String uname, String uPassword");
		    	
		    	     List<MinesweeperRegistration>   list1 = (List<MinesweeperRegistration>) query.execute(uname,password);
		    	
		    	    if(list1.size() > 0) {
		    	    	
		    	    	return true;
		    	    }
		    } finally {
		      pm.close();
		    }
			return false;
			
	}

//	private PersistenceManager getPersistenceManager() {
//		return PMF.getPersistenceManager();
//	}

	public UserInfo getSessions() {
		
		HttpSession httpSession = getThreadLocalRequest().getSession(true);
		if(httpSession.getAttribute("userName")!=null) {
			return (UserInfo)httpSession.getAttribute("userName");
		}
		else{
			return null;
		}
		
	}
	
	public UserInfo logout() {
		
		HttpSession httpSession = getThreadLocalRequest().getSession(true);
		httpSession.setAttribute("userName", null);
		UserInfo out = (UserInfo)httpSession.getAttribute("userName");
		System.out.print(out);
		return null;
	}

	@Override
	public List<LoginInfo> listUsers() {
		// TODO Auto-generated method stub
		return null;
	}

}



